//JSON工具类
package com.cuijian.demo.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jfinal.core.Controller;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

public class JsonUtil {

    /**
     * 从请求中读取JSON数据并转换为JSONObject
     */
    public static JSONObject getJsonData(Controller controller) {
        HttpServletRequest request = controller.getRequest();
        StringBuilder sb = new StringBuilder();

        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException("读取JSON数据失败", e);
        }

        if (sb.length() == 0) {
            return new JSONObject();
        }

        return JSON.parseObject(sb.toString());
    }

    /**
     * 从请求中读取JSON数据并转换为指定类型
     */
    public static <T> T getJsonData(Controller controller, Class<T> clazz) {
        String jsonString = getJsonString(controller);
        if (jsonString == null || jsonString.trim().isEmpty()) {
            return null;
        }
        return JSON.parseObject(jsonString, clazz);
    }

    /**
     * 获取原始JSON字符串
     */
    public static String getJsonString(Controller controller) {
        HttpServletRequest request = controller.getRequest();
        StringBuilder sb = new StringBuilder();

        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException("读取JSON数据失败", e);
        }

        return sb.toString();
    }

    /**
     * 检查请求内容类型是否为JSON
     */
    public static boolean isJsonRequest(Controller controller) {
        String contentType = controller.getRequest().getContentType();
        return contentType != null &&
                (contentType.contains("application/json") ||
                        contentType.contains("application/json;charset=UTF-8"));
    }
}